package com.bizmda.bizsip.sample.source.longtcpnetty;

import com.bizmda.bizsip.common.BizUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: 史正烨
 * @Date: 2022/3/1 2:03 下午
 * @Description:
 */
@Slf4j
public class NettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    /**
     * 客户端连接会触发
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.debug("Channel通道激活:{}-{}",ctx.channel().localAddress(),ctx.channel().remoteAddress());
    }


    /**
     * 取消绑定
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.debug("Channel通道失效:{}-{}",ctx.channel().localAddress(),ctx.channel().remoteAddress());
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent){
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt ;

            if (idleStateEvent.state() == IdleState.WRITER_IDLE){
                log.debug("写空闲超时,发送心跳检测包!");
                //向服务端发送消息
                SampleMessage message = SampleMessage.builder().length((short) 0).data(new byte[0]).build();
                ctx.writeAndFlush(message).addListener(ChannelFutureListener.CLOSE_ON_FAILURE) ;
            }
        }
        super.userEventTriggered(ctx, evt);
    }


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf in) throws Exception {
        //从服务端收到消息时被调用
        byte[] bytes = new byte[in.readableBytes()];
        in.readBytes(bytes);
        log.debug("客户端收到消息:\n{}", BizUtils.buildHexLog(bytes)) ;    }
}